#include "BinObjWriter.h"
#include "MeshList.h"
#include "ObjMesh.h"
#include "TriangleList.h"

BinObjWriter::BinObjWriter(tstring filename):BinaryWriter(filename)
{
}

BinObjWriter::~BinObjWriter(void)
{
}

bool BinObjWriter::WriteMaterialFile(tstring& materialFile)
{
	if (m_Open){
		OBJECTTYPE type = MATERIALFILE;
		m_Output.write((char*)&type,sizeof(OBJECTTYPE));
		WriteString(materialFile);
		return true;
	}
	return false;
}

bool BinObjWriter::WriteSkeletonFile(tstring& skeletonFile)
{
	if (m_Open){
		OBJECTTYPE type = SKELETONFILE;
		m_Output.write((char*)&type,sizeof(OBJECTTYPE));
		WriteString(skeletonFile);
		return true;
	}
	return false;
}

bool BinObjWriter::WriteVertexList(VertexList* vertexList )
{
	if (m_Open){
		OBJECTTYPE type = VERTEXLIST;
		m_Output.write((char*)&type,sizeof(OBJECTTYPE));
		WriteCommonVertexList(vertexList);
		return true;
	}else
		return false;

}

bool BinObjWriter::WriteVertexList(VertexList* vertexList,tstring& skeletonFile )
{
	if (m_Open){
		OBJECTTYPE type = VERTEXLIST;
		m_Output.write((char*)&type,sizeof(OBJECTTYPE));
		
		if ( skeletonFile.size() > 0) 
			WriteSkeletonFile(skeletonFile);
		WriteCommonVertexList(vertexList);
		return true;
	}else
		return false;

}

void BinObjWriter::WriteCommonVertexList(VertexList* vertexList)
{
	OBJECTTYPE vertexData  = VERTEXDATA;
	m_Output.write((char*)&vertexData,sizeof(OBJECTTYPE));

	int sizeInBytes = vertexList->GetSize()*vertexList->GetSizePerVertexInBytes();
	m_Output.write((char*)&sizeInBytes,sizeof(int));

	int nrOfVertices = vertexList->GetSize();
	m_Output.write((char*)&nrOfVertices,sizeof(int));

	int nrOfSemantics = vertexList->GetNumberOfSemantics();
	m_Output.write((char*)&nrOfSemantics,sizeof(int));

	for ( int i = 0 ; i< nrOfSemantics; ++i)
	{
		SEMANTIC s = vertexList->GetSemantic(i);
		m_Output.write((char*)&s,sizeof(SEMANTIC));

		int size = vertexList->GetSemanticSize(i);
		m_Output.write((char*)&size,sizeof(int));
	}
	m_Output.write((char*)vertexList->GetData(),sizeInBytes);
}

bool BinObjWriter::WriteTriangleList(TriangleList* triangleList, tstring& materialName)
{
	if (m_Open){
		OBJECTTYPE type = TRIANGLELIST;
		m_Output.write((char*)&type,sizeof(OBJECTTYPE));

		// write the material file.
		
		OBJECTTYPE materialType = MATERIALNAME;
		m_Output.write((char*)&materialType,sizeof(OBJECTTYPE));
		this->WriteString(materialName);


		OBJECTTYPE triangleDataType = TRIANGLEDATA;
		m_Output.write((char*)&triangleDataType,sizeof(OBJECTTYPE));

		int sizeInBytes = triangleList->GetSizeInBytes();
		m_Output.write((char*)&sizeInBytes,sizeof(int));

		int nrOfTriangles = triangleList->GetNumberOfPrimitives();
		m_Output.write((char*)&nrOfTriangles,sizeof(int));

		m_Output.write((char*)triangleList->GetData(),sizeInBytes);
		return true;
	}else{
		return false;
	}
}